import { getNumAndUnit, mergeNumAndUnit } from '@/utils/utils'
import { AM_UNIT, RATE_UNIT, TIME_UNIT } from '@/constant'
import { round } from 'lodash'
import useChartsStore from '@/store/modules/charts'
import useDmFormStore from '@/store/modules/form/dmForm'
import useZpFormStore from '@/store/modules/form/zpForm'
import useHarmonicFormStore from '@/store/modules/form/harmonicForm'
import useScanFormStore from '@/store/modules/form/scanForm'
import useRadarScanormStore from '@/store/modules/form/radarScanForm'


export default class ModelData {
  constructor(fields = [], type = 'dm') {
    this.fields = fields
    this.global = useChartsStore().global
    if (type == 'dm') {
      this.form = useDmFormStore()
    } else if (type === 'zp') {
      this.form = useZpFormStore()
    } else if (type === 'scan') {
      this.form = useScanFormStore()
    } else if (type === 'radarScan') {
      this.form = useRadarScanormStore()
    }else {
      this.form = useHarmonicFormStore()
    }
    this.generateModel(fields)
  }
  generateModel(fields) {
    fields.forEach(field => {
      const key = field.target
      if (field.appendSelect && !field.unitType) {
        field.unitType = this.generateUnitType(field)
      }
      this[key] = this.generatePropery(key, field)
    })
  }
  generateUnitType({ options }) {
    if (options.includes('s')) {
      return 1
    } else if (options.includes('dBm')) {
      return 2
    } else {
      return 0
    }
  }
  generatePropery(key, field) {
    const units = [RATE_UNIT, TIME_UNIT, AM_UNIT]
    if (!field.appendSelect) {
      if (this.global[key] !== undefined) {
        return field.int ? round(this.global[key]) : this.global[key]
      } else {
        return field.int ? round(this.form[key]) : this.form[key]
      }
    }
    if (this.global[key] !== undefined) {
      return getNumAndUnit(this.global[key], field.unitType)
    } else {
      return getNumAndUnit(this.form[key], field.unitType)
    }
  }
  setVal(key, val) {
    const { global, setGlobal } = useChartsStore()
    const field = this.fields.find(item => item.target === key)
    if (!field || field.disabled) {
      return
    }
    if (field.appendSelect) {
      if (global[key] !== undefined) {
        setGlobal(key, mergeNumAndUnit(val + this[key].unit, field.unitType))
      } else if (this.form) {
        this.form[key] = mergeNumAndUnit(val + this[key].unit, field.unitType)
      }
    } else {
      if (global[key] !== undefined) {
        global[key] = typeof val === 'string' ? parseInt(val) : val
      } else if (this.form) {
        this.form[key] = typeof val === 'string' ? parseInt(val) : val
      }
    }
  }
  update() {
    this.generateModel(this.fields)
  }
  updateItem(key, field) {
    this[key] = this.generatePropery(key, field)
  }
}
